import { PagePath } from '@/common/constants'
import { useUserStore } from '@/common/store'

/** 需要拦截的路径 */
const interceptPath = [
  PagePath.SETTING,
  PagePath.MY_LIST,
  PagePath.NOTIFICATION,
  PagePath.NOTIFICATION_DETAIL,
  PagePath.CREATE_ACTIVITY,
  PagePath.CREATE_NOTIFICATION,
  PagePath.CREATE_PROJECT,
  PagePath.CREATE_DYNAMIC,
]

/**
 * 路由拦截器
 * @author lian
 */
export const routeInterception = () => {
  const list = ['navigateTo', 'redirectTo', 'reLaunch', 'switchTab']

  list.forEach((item) => {
    uni.addInterceptor(item, {

      invoke(e) {
        const { hope_token } = useUserStore()
        // 获取路径
        const url = e.url.split('?')[0]

        // 判断是否需要拦截 以及 用户是否登录
        if (interceptPath.includes(url) && hope_token === null) {
          showSimpleToast(PLEASE_LOGIN)

          // 跳转到登录页
          goToPage(PagePath.LOGIN)
          return false
        }

        return true
      },

      // 失败回调拦截
      fail(err) {
        console.log(err)
      },
    })
  })
}
